package org.rency.mq.activemq.listener.failover.impl;

import org.rency.mq.activemq.jms.service.JmsAccessor;
import org.rency.mq.activemq.listener.failover.FailoverService;
import org.rency.mq.activemq.listener.failover.RetryExecutor;
import org.rency.mq.activemq.request.MQRequest;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class TimerRetryExecutor implements RetryExecutor {
	private JmsAccessor mqAccessor;
	private ScheduledExecutorService executorService;
	
	public TimerRetryExecutor(JmsAccessor mqAccessor){
		this.mqAccessor = mqAccessor;
	}

	public JmsAccessor getMqAccessor() {
		return mqAccessor;
	}

	public void retrySend(MQRequest request) throws Exception {
		if (executorService == null) {
			throw new Exception("Must assign the executorService when it doesn't support schedule message.");
		}
		long retryInterval = 0;
		if (request.containsProperty(FailoverService.AMQ_SCHEDULED_DELAY)) {
			retryInterval = Long.parseLong(request.getProperty(FailoverService.AMQ_SCHEDULED_DELAY).toString());
		}
		executorService.schedule(new RetryTask(getMqAccessor(), request),retryInterval, TimeUnit.MILLISECONDS);
	}

	public void setExecutorService(ScheduledExecutorService executorService) {
		this.executorService = executorService;
	}

}
